<template>
  <div class="users-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">用户管理</h1>
        <div class="status-badges">
          <el-tag type="primary" class="total-badge">
            <el-icon><User /></el-icon>
            总用户: {{ stats.totalUsers }}
          </el-tag>
          <el-tag type="success" class="active-badge">
            <el-icon><TrendCharts /></el-icon>
            活跃用户: {{ stats.activeUsers }}
          </el-tag>
          <el-tag type="warning" class="admin-badge">
            <el-icon><Lock /></el-icon>
            管理员: {{ stats.adminUsers }}
          </el-tag>
          <el-tag type="info" class="online-badge">
            <el-icon><Connection /></el-icon>
            在线用户: {{ stats.onlineUsers }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 新增用户 -->
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="showCreateUserDialog"
        >
          新增用户
        </el-button>
        
        <!-- 批量导入 -->
        <el-button 
          :icon="Upload" 
          @click="showImportDialog"
        >
          批量导入
        </el-button>
        
        <!-- 批量操作 -->
        <el-button 
          :icon="Operation" 
          @click="showBatchOperations"
          :disabled="selectedUsers.length === 0"
        >
          批量操作 ({{ selectedUsers.length }})
        </el-button>
        
        <!-- 用户分组 -->
        <el-button 
          :icon="Collection" 
          @click="showGroupManagement"
        >
          用户分组
        </el-button>
        
        <!-- 导出用户 -->
        <el-button :icon="Download" @click="exportUsers">
          导出用户
        </el-button>
        
        <!-- 刷新数据 -->
        <el-button 
          :icon="Refresh" 
          @click="loadUsers"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="本月新增用户"
          :value="stats.newUsersThisMonth"
          :icon="UserFilled"
          color="#1890ff"
          :trend="stats.newUserTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="用户活跃度"
          :value="stats.activityRate"
          suffix="%"
          :icon="TrendCharts"
          color="#52c41a"
          :trend="stats.activityTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="用户留存率"
          :value="stats.retentionRate"
          suffix="%"
          :icon="SuccessFilled"
          color="#fa8c16"
          :trend="stats.retentionTrend"
        />
      </el-col>
      <el-col :xs="24" :sm="6">
        <MetricCard
          title="平均登录次数"
          :value="stats.avgLoginCount"
          :icon="Star"
          color="#722ed1"
          :trend="stats.loginTrend"
        />
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="用户状态">
          <el-select v-model="queryParams.status" clearable placeholder="全部状态" style="width: 120px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="锁定" value="locked" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户角色">
          <el-select v-model="queryParams.role" clearable placeholder="全部角色" style="width: 120px">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="审核员" value="auditor" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户名">
          <el-input
            v-model="queryParams.name"
            placeholder="输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input
            v-model="queryParams.email"
            placeholder="输入邮箱"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>用户列表</span>
          <div class="table-actions">
            <el-button-group>
              <el-button :icon="Sort" @click="handleSort('created_at')">
                按创建时间
              </el-button>
              <el-button :icon="Sort" @click="handleSort('last_login')">
                按最后登录
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        ref="userTableRef"
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="handleSortChange"
        class="users-table"
      >
        <el-table-column type="selection" width="50" />
        
        <!-- 用户基本信息 -->
        <el-table-column prop="basicInfo" label="用户信息" min-width="250" fixed>
          <template #default="{ row }">
            <div class="user-basic-cell">
              <div class="user-name-row">
                <span class="user-name">{{ row.name }}</span>
                <el-tag 
                  v-if="row.role === 'admin'" 
                  type="danger" 
                  size="small"
                  class="role-tag"
                >
                  管理员
                </el-tag>
                <el-tag 
                  v-else-if="row.role === 'user'" 
                  type="primary" 
                  size="small"
                  class="role-tag"
                >
                  用户
                </el-tag>
                <el-tag 
                  v-else-if="row.role === 'auditor'" 
                  type="warning" 
                  size="small"
                  class="role-tag"
                >
                  审核员
                </el-tag>
              </div>
              <div class="user-email" v-if="row.email">
                {{ row.email }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <!-- 账户状态 -->
        <el-table-column prop="status" label="账户状态" width="120">
          <template #default="{ row }">
            <el-tag 
              :type="getUserStatusType(row.status)"
              size="small"
            >
              {{ getUserStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 最后登录 -->
        <el-table-column prop="lastLogin" label="最后登录" width="160" sortable>
          <template #default="{ row }">
            <div class="last-login-cell">
              <div class="login-time" v-if="row.lastLoginAt">
                {{ formatDate(row.lastLoginAt) }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <!-- 创建时间 -->
        <el-table-column prop="createdAt" label="创建时间" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                link 
                :icon="View" 
                @click.stop="handleShowUserDetail(row)"
              >
                详情
              </el-button>
              
              <el-button 
                type="success" 
                link 
                :icon="Edit" 
                @click.stop="handleEditUser(row)"
              >
                编辑
              </el-button>
              
              <el-dropdown 
                @command="(command: string) => handleMoreAction(command, row)"
              >
                <el-button type="info" link :icon="More" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item 
                      command="resetPassword" 
                      :icon="Refresh"
                    >
                      重置密码
                    </el-dropdown-item>
                    <el-dropdown-item 
                      command="toggleStatus" 
                      :icon="Lock"
                      v-if="row.status === 'active'"
                    >
                      禁用账户
                    </el-dropdown-item>
                    <el-dropdown-item 
                      command="toggleStatus" 
                      :icon="Unlock"
                      v-else
                    >
                      启用账户
                    </el-dropdown-item>
                    <el-dropdown-item 
                      command="delete" 
                      :icon="Delete"
                      divided
                    >
                      删除用户
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户导入向导 -->
    <UserImportWizard 
      v-model="importWizardVisible" 
      @import-success="handleImportSuccess" 
    />
    
    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="editingUser.id ? '编辑用户' : '新增用户'"
      width="500px"
    >
      <el-form :model="editingUser" label-width="80px" ref="userFormRef">
        <el-form-item label="用户名" prop="name" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="editingUser.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :rules="[{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }]">
          <el-input v-model="editingUser.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="[{ required: !editingUser.id, message: '请输入密码', trigger: 'blur' }]">
          <el-input v-model="editingUser.password" placeholder="请输入密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role" :rules="[{ required: true, message: '请选择角色', trigger: 'change' }]">
          <el-select v-model="editingUser.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="审核员" value="auditor" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editingUser.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="锁定" value="locked" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 用户详情抽屉 -->
    <el-drawer
      v-model="detailDialogVisible"
      title="用户详情"
      direction="rtl"
      size="500px"
    >
      <div class="drawer-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户ID">{{ detailUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ detailUser.name }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ detailUser.email }}</el-descriptions-item>
          <el-descriptions-item label="角色">{{ getRoleText(detailUser.role) }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getUserStatusText(detailUser.status) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(detailUser.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(detailUser.updatedAt) }}</el-descriptions-item>
          <el-descriptions-item label="最后登录" v-if="detailUser.lastLoginAt">{{ formatDate(detailUser.lastLoginAt) }}</el-descriptions-item>
          <el-descriptions-item label="用户分组">
            <el-tag 
              v-for="group in userGroups.filter((g: UserGroup) => g.memberIds?.includes(detailUser.id))"
              :key="group.id"
              type="primary"
              style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ group.name }}
            </el-tag>
            <el-button 
              type="primary" 
              link 
              @click="showAddToGroupDialog(detailUser)"
              style="margin-left: 10px;"
            >
              添加到分组
            </el-button>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-drawer>
    
    <!-- 用户分组管理对话框 -->
    <el-dialog
      v-model="groupManagementDialogVisible"
      title="用户分组管理"
      width="800px"
      @open="loadUserGroups"
    >
      <div class="group-management-content">
        <!-- 左侧：分组列表 -->
        <div class="group-list">
          <div class="group-list-header">
            <el-button type="primary" @click="showCreateGroupDialog">
              <el-icon><Plus /></el-icon>
              新建分组
            </el-button>
          </div>
          <el-table :data="userGroups" style="width: 100%" highlight-current-row>
            <el-table-column prop="name" label="分组名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="memberCount" label="成员数" width="80" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button link type="primary" @click="editGroup(row)">编辑</el-button>
                <el-button link type="danger" @click="deleteGroup(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 右侧：分组详情 -->
        <div class="group-detail">
          <el-card v-if="editingGroup" shadow="never">
            <template #header>
              <div class="card-header">
                <span>{{ editingGroup.id ? '编辑分组' : '新建分组' }}</span>
              </div>
            </template>
            <el-form :model="editingGroup" label-width="80px">
              <el-form-item label="分组名称">
                <el-input v-model="editingGroup.name" placeholder="请输入分组名称" />
              </el-form-item>
              <el-form-item label="描述">
                <el-input 
                  v-model="editingGroup.description" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入分组描述" 
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveGroup">保存</el-button>
                <el-button @click="cancelEditGroup">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-card v-else shadow="never" class="empty-detail">
            <el-empty description="请选择一个分组进行编辑" />
          </el-card>
        </div>
      </div>
    </el-dialog>
    
    <!-- 添加到分组对话框 -->
    <el-dialog
      v-model="addToGroupDialogVisible"
      title="添加到分组"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="用户">
          <div>{{ currentUserToAdd?.name }}</div>
        </el-form-item>
        
        <el-form-item label="选择分组">
          <el-select 
            v-model="selectedGroupId" 
            placeholder="请选择分组" 
            style="width: 100%"
            filterable
          >
            <el-option 
              v-for="group in userGroups" 
              :key="group.id" 
              :label="group.name" 
              :value="group.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addToGroupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddToGroup">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchOperationDialogVisible"
      title="批量操作"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="已选择用户">
          <el-tag v-for="user in selectedUsers" :key="user.id" style="margin-right: 5px; margin-bottom: 5px;">
            {{ user.name }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="操作类型">
          <el-select v-model="batchOperationType" placeholder="请选择操作类型" style="width: 100%">
            <el-option label="批量删除" value="delete" />
            <el-option label="批量启用" value="enable" />
            <el-option label="批量禁用" value="disable" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="batchOperationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchOperation">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { ref, reactive, onMounted } from 'vue'
// @ts-ignore
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, TrendCharts, Lock, Connection, Plus, Upload, Operation, 
  Collection, Download, Refresh, Search, Sort, View, Edit, More, Delete, Unlock,
  UserFilled, SuccessFilled, Star
} from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/appStore'
import MetricCard from '@/views/dashboard/components/MetricCard.vue'
import UserImportWizard from './components/UserImportWizard.vue'
// @ts-ignore
import { useUserManagement } from '@/composables/useUserManagement'

// Store
const appStore = useAppStore()

// 使用用户管理composable
// @ts-ignore
const {
  // 数据
  loading,
  saving,
  selectedUsers,
  tableData,
  pagination,
  editingUser,
  detailUser,
  queryParams,
  
  // 方法
  loadUsers,
  handleSearch,
  handleReset,
  handleSelectionChange,
  showUserDetail,
  editUser,
  saveUser,
  deleteUser,
  batchDeleteUsers,
  batchUpdateUserStatus,
  resetUserPassword: resetUserPasswordFromComposable,
  toggleUserStatus,
  showBatchOperations: showBatchOperationsFromComposable,
  handleSizeChange,
  handleCurrentChange,
  // 用户分组相关方法
  loadUserGroups: loadUserGroupsFromComposable,
  createUserGroup: createUserGroupFromComposable,
  updateUserGroup: updateUserGroupFromComposable,
  deleteUserGroup: deleteUserGroupFromComposable,
  getGroupMembers: getGroupMembersFromComposable,
  addUserToGroup: addUserToGroupFromComposable,
  removeUserFromGroup: removeUserFromGroupFromComposable
} = useUserManagement()

// 类型定义
interface UserGroup {
  id: number
  name: string
  description: string
  memberCount: number
  memberIds?: number[]
}

interface UserItem {
  id: number
  name: string
  email: string
  role: string
  status: string
  lastLoginAt?: string
  createdAt: string
  updatedAt: string
}

// 用户分组相关
const userGroups = ref<UserGroup[]>([])
const editingGroup = ref<UserGroup | null>(null)
const addToGroupDialogVisible = ref(false)
const selectedGroupId = ref<number | null>(null)
const currentUserToAdd = ref<UserItem | null>(null)

// 包装editUser方法以确保对话框显示
const handleEditUser = async (user: UserItem) => {
  try {
    // 直接设置editingUser的值
    editingUser.value = { ...user, password: '' }
    // 设置对话框可见
    userDialogVisible.value = true
  } catch (error) {
    console.error('编辑用户失败:', error)
  }
}

// 包装saveUser方法以确保保存后关闭对话框
const handleSaveUser = async () => {
  try {
    // 调用composable中的saveUser方法
    await saveUser()
    // 保存成功后关闭对话框
    userDialogVisible.value = false
  } catch (error) {
    console.error('保存用户失败:', error)
  }
}

// 包装showUserDetail方法以确保显示抽屉
const handleShowUserDetail = async (user: UserItem) => {
  try {
    // 调用composable中的showUserDetail方法获取用户详情
    await showUserDetail(user)
    // 显示详情抽屉
    detailDialogVisible.value = true
  } catch (error) {
    console.error('显示用户详情失败:', error)
  }
}

// 显示添加到分组对话框
const showAddToGroupDialog = (user: UserItem) => {
  currentUserToAdd.value = user
  selectedGroupId.value = null
  addToGroupDialogVisible.value = true
}

// 处理添加到分组
const handleAddToGroup = async () => {
  if (!currentUserToAdd.value || !selectedGroupId.value) {
    ElMessage.warning('请选择分组')
    return
  }
  
  try {
    await addUserToGroupFromComposable(currentUserToAdd.value.id, selectedGroupId.value)
    ElMessage.success('用户已添加到分组')
    addToGroupDialogVisible.value = false
    // 重新加载分组数据
    await loadUserGroups()
  } catch (error) {
    console.error('添加到分组失败:', error)
  }
}

// 对话框相关
const userDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const importWizardVisible = ref(false)
const groupManagementDialogVisible = ref(false)
const batchOperationDialogVisible = ref(false)

// 批量操作相关
const batchOperationType = ref('')

// 表单引用
const userTableRef = ref()
const userFormRef = ref()

// 统计信息
const stats = reactive({
  totalUsers: 0,
  activeUsers: 0,
  adminUsers: 0,
  onlineUsers: 0,
  newUsersThisMonth: 0,
  activityRate: 0,
  retentionRate: 0,
  avgLoginCount: 0,
  newUserTrend: 0,
  activityTrend: 0,
  retentionTrend: 0,
  loginTrend: 0
})

// 工具函数
const getUserStatusType = (status: string) => {
  const typeMap: Record<string, any> = {
    active: 'success',
    inactive: 'info',
    locked: 'warning'
  }
  return typeMap[status] || 'info'
}

const getUserStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    active: '启用',
    inactive: '禁用',
    locked: '锁定'
  }
  return textMap[status] || status
}

const getRoleText = (role: string) => {
  const textMap: Record<string, string> = {
    admin: '管理员',
    user: '普通用户',
    auditor: '审核员'
  }
  return textMap[role] || role
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const handleRowClick = (row: any) => {
  // 可以显示快速详情
  console.log('点击用户:', row)
}

const handleSort = (field: string) => {
  // 排序逻辑可以根据需要实现
  loadUsers()
}

const handleSortChange = ({ prop, order }: any) => {
  // 排序逻辑可以根据需要实现
  loadUsers()
}

const showCreateUserDialog = () => {
  // 重置表单
  editingUser.value = {
    id: 0,
    name: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active'
  }
  userDialogVisible.value = true
}

const showImportDialog = () => {
  importWizardVisible.value = true
}

const showBatchOperations = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  
  // 重置批量操作类型
  batchOperationType.value = ''
  
  // 显示批量操作对话框
  batchOperationDialogVisible.value = true
}



const handleBatchOperation = async () => {
  if (!batchOperationType.value) {
    ElMessage.warning('请选择操作类型')
    return
  }
  
  try {
    const selectedUserIds = selectedUsers.value.map((user: any) => user.id)
    
    switch (batchOperationType.value) {
      case 'delete':
        // 确认删除
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复。`,
          '删除确认',
          {
            type: 'warning'
          }
        )
        
        await batchDeleteUsers(selectedUserIds)
        // 清空选择
        selectedUsers.value = []
        break
        
      case 'enable':
        // 启用用户
        await batchUpdateUserStatus(selectedUserIds, 'active')
        // 清空选择
        selectedUsers.value = []
        break
        
      case 'disable':
        // 禁用用户
        await batchUpdateUserStatus(selectedUserIds, 'inactive')
        // 清空选择
        selectedUsers.value = []
        break
        
      default:
        ElMessage.warning('未知的操作类型')
        return
    }
    
    // 关闭对话框
    batchOperationDialogVisible.value = false
    ElMessage.success('操作成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

const showGroupManagement = () => {
  groupManagementDialogVisible.value = true
}

const exportUsers = async () => {
  try {
    loading.value = true
    // 这里可以调用导出API
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

const handleImportSuccess = () => {
  loadUsers()
}

// 用户分组管理方法
const loadUserGroups = async () => {
  try {
    // 加载分组列表
    const groups = await loadUserGroupsFromComposable()
    
    // 为每个分组获取成员信息
    const groupsWithMembers = await Promise.all(groups.map(async (group: UserGroup) => {
      const members = await getGroupMembersFromComposable(group.id)
      return {
        ...group,
        memberIds: members.map((member: any) => member.userId)
      }
    }))
    
    userGroups.value = groupsWithMembers
  } catch (error) {
    ElMessage.error('加载用户分组失败')
  }
}

const createUserGroup = async (groupData: { name: string; description?: string }) => {
  try {
    await createUserGroupFromComposable(groupData)
    // 重新加载分组列表
    await loadUserGroups()
    ElMessage.success('分组创建成功')
  } catch (error) {
    ElMessage.error('创建分组失败')
  }
}

const updateUserGroup = async (id: number, groupData: { name?: string; description?: string }) => {
  try {
    await updateUserGroupFromComposable(id, groupData)
    // 重新加载分组列表
    await loadUserGroups()
    ElMessage.success('分组更新成功')
  } catch (error) {
    ElMessage.error('更新分组失败')
  }
}

const showCreateGroupDialog = () => {
  editingGroup.value = { id: 0, name: '', description: '', memberCount: 0 }
}

const editGroup = (group: any) => {
  editingGroup.value = { ...group }
}

const saveGroup = async () => {
  if (!editingGroup.value.name) {
    ElMessage.warning('请输入分组名称')
    return
  }
  
  try {
    if (editingGroup.value.id) {
      // 更新现有分组
      await updateUserGroup(editingGroup.value.id, {
        name: editingGroup.value.name,
        description: editingGroup.value.description
      })
    } else {
      // 创建新分组
      await createUserGroup({
        name: editingGroup.value.name,
        description: editingGroup.value.description
      })
    }
    
    editingGroup.value = null
  } catch (error) {
    ElMessage.error('保存分组失败')
  }
}

const cancelEditGroup = () => {
  editingGroup.value = null
}

const deleteGroup = async (group: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分组 "${group.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        type: 'warning'
      }
    )
    
    await deleteUserGroupFromComposable(group.id)
    
    const index = userGroups.value.findIndex((g: UserGroup) => g.id === group.id)
    if (index !== -1) {
      userGroups.value.splice(index, 1)
    }
    
    ElMessage.success('分组删除成功')
    
    // 如果正在编辑的分组被删除，清空编辑状态
    if (editingGroup.value && editingGroup.value.id === group.id) {
      editingGroup.value = null
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除分组失败')
    }
  }
}

// 重写resetUserPassword方法以适配当前组件需求
const resetUserPassword = async (user: UserItem) => {
  try {
    await ElMessageBox.prompt('请输入新密码', '重置密码', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'password',
      inputPlaceholder: '请输入新密码'
    }).then(async ({ value }: { value: string }) => {
      if (!value) {
        ElMessage.warning('密码不能为空')
        return
      }
      
      // 调用composable中的重置密码方法
      await resetUserPasswordFromComposable(user.id, value)
      ElMessage.success('密码重置成功')
    }).catch(() => {
      // 用户取消操作
    })
  } catch (error: any) {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  }
}

const handleMoreAction = async (command: string, user: UserItem) => {
  switch (command) {
    case 'resetPassword':
      await resetUserPassword(user)
      break
    case 'toggleStatus':
      await toggleUserStatus(user)
      break
    case 'delete':
      await deleteUser(user)
      break
  }
}

const loadStats = async () => {
  // 这里可以调用获取统计信息的API
  // 暂时使用模拟数据
  stats.totalUsers = 128
  stats.activeUsers = 96
  stats.adminUsers = 5
  stats.onlineUsers = 24
  stats.newUsersThisMonth = 12
  stats.activityRate = 85.5
  stats.retentionRate = 92.3
  stats.avgLoginCount = 15
  stats.newUserTrend = 5
  stats.activityTrend = 2.3
  stats.retentionTrend = -1.2
  stats.loginTrend = 0.8
}

// 生命周期
onMounted(() => {
  appStore.setPageTitle('用户管理')
  loadUsers()
  loadStats()
})
</script>

<style scoped lang="scss">
.users-management {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .header-left {
      .page-title {
        margin: 0 0 12px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2d3d;
      }
      
      .status-badges {
        display: flex;
        gap: 12px;
        
        .el-tag {
          display: flex;
          align-items: center;
          gap: 4px;
          font-weight: 500;
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-row {
    margin-bottom: 20px;
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
    }
    
    .users-table {
      :deep(.el-table__row) {
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: #f5f7fa;
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
      
      .user-basic-cell {
        .user-name-row {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
          
          .user-name {
            font-weight: 500;
          }
          
          .role-tag {
            margin-left: auto;
          }
        }
        
        .user-email,
        .user-phone {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .last-login-cell {
        .login-time {
          font-weight: 500;
          margin-bottom: 2px;
        }
        
        .login-ip {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .login-count-cell {
        font-weight: 500;
        text-align: center;
      }
      
      .action-buttons {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
  }
  
  .group-management-content {
    display: flex;
    gap: 20px;
    
    .group-list {
      flex: 1;
      
      .group-list-header {
        margin-bottom: 15px;
        text-align: right;
      }
    }
    
    .group-detail {
      width: 300px;
      
      .empty-detail {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .users-management {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      gap: 16px;
      
      .status-badges {
        flex-wrap: wrap;
      }
      
      .header-actions {
        flex-wrap: wrap;
        justify-content: center;
      }
    }
  }
}

// 抽屉样式
.drawer-content {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .el-descriptions {
    margin-bottom: 20px;
  }
}
</style>